package com.manage.system.aspect;

import com.alibaba.fastjson.JSON;
import com.manage.system.entity.RequestErrorInfo;
import com.manage.system.entity.RequestInfo;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author liuzhao
 * @Date 2023/2/27 21:56
 * @Content 调用请求参数打印切面
 * @Version 1.0
 */
@Log4j2
@Aspect
@Component
public class RequestLogAspect {

    @Pointcut("execution(* com.manage.system.controller.* ..* (..))")
    public void requestServer() {

    }

    /**
     * 请求开始打印请求参数
     * @param proceedingJoinPoint   切入点对象
     * @return                      请求执行结果
     * @throws Throwable            异常
     */
    @Around("requestServer()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object proceed = proceedingJoinPoint.proceed();
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setIp(request.getRemoteAddr());
        requestInfo.setUrl(request.getRequestURL().toString());
        requestInfo.setHttpMethod(request.getMethod());
        requestInfo.setClassMethod(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(), proceedingJoinPoint.getSignature().getName()));
        requestInfo.setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));
        requestInfo.setResult(proceed);
        requestInfo.setTimeCost(System.currentTimeMillis() - start);
        log.info("Result Info : {}", JSON.toJSONString(requestInfo));
        return proceed;
    }

    /**
     * 请求抛出的异常处理
     * @param joinPoint 切入点对象
     * @param e         异常
     */
    @AfterThrowing(pointcut = "requestServer()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, Exception e) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        RequestErrorInfo requestErrorInfo = new RequestErrorInfo();
        requestErrorInfo.setIp(request.getRemoteAddr());
        requestErrorInfo.setUrl(request.getRequestURL().toString());
        requestErrorInfo.setHttpMethod(request.getMethod());
        requestErrorInfo.setClassMethod(String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()));
        requestErrorInfo.setRequestParams(getRequestParamsByJoinPoint(joinPoint));
        requestErrorInfo.setException(e);
        log.info("Error Request Info : {}", requestErrorInfo);
    }

    private Object getRequestParamsByProceedingJoinPoint(ProceedingJoinPoint proceedingJoinPoint) {
        // 参数名
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        String[] parameterNames = signature.getParameterNames();
        // 参数值
        Object[] parameterValue = proceedingJoinPoint.getArgs();
        return buildRequestParam(parameterNames, parameterValue);
    }

    private Object getRequestParamsByJoinPoint(JoinPoint joinPoint) {
        // 参数名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = signature.getParameterNames();
        // 参数值
        Object[] parameterValue = joinPoint.getArgs();
        return buildRequestParam(parameterNames, parameterValue);
    }

    /**
     * 组装请求参数
     * @param parameterNames    参数名称
     * @param parameterValue    参数值
     * @return                  组装参数
     */
    private Object buildRequestParam(String[] parameterNames, Object[] parameterValue) {
        Map<String, Object> requestParams = new HashMap<>();
        for (int i = 0; i < parameterNames.length; i++) {
            Object value = parameterValue[i];
            // 判断是否为文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                // 获取文件名
                value = file.getOriginalFilename();
            }
            // 如果是批量上传文件
            if (value instanceof List) {
                try {
                    List<MultipartFile> multipartFiles = castList(value, MultipartFile.class);
                    if (CollectionUtils.isEmpty(multipartFiles)) {
                        List<String> fileNames = new ArrayList<>();
                        for (MultipartFile multipartFile : multipartFiles) {
                            fileNames.add(multipartFile.getOriginalFilename());
                        }
                        requestParams.put(parameterNames[i], fileNames);
                    } else {
                        requestParams.put(parameterNames[i], value);
                    }
                } catch (Exception e) {
                    log.error("获取请求参数失败：{}", e.toString());
                }
            } else {
                requestParams.put(parameterNames[i], value);
            }
        }
        return requestParams;
    }

    private static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        for (Object o : (List<?>) obj) {
            if (obj instanceof MultipartFile) {
                result.add(clazz.cast(o));
            }
        }
        return result;
    }
}
